package cn.edu.upc.letao.redisRepository;

import cn.edu.upc.letao.entity.PoolLabel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * Created by 风飞扬 on 2017/6/26.
 */
@Repository
public class LabelRepositoryImpl implements LabelRepository {

    private static final String KEY = "label";

    private RedisTemplate<String, PoolLabel> redisTemplate;
    private HashOperations hashOps;

    @Autowired
    public LabelRepositoryImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostConstruct
    private void init() {
        hashOps = redisTemplate.opsForHash();
    }


    //增或者改
    @Override
    public boolean saveLabel(PoolLabel label) {
        if(label==null){
            return false;
        }

        hashOps.put(KEY, label.getLabelid(), label);
        return true;
    }

    //根据标签id删除标签
    @Override
    public boolean delLabel(Integer labelid) {
        if(labelid==null){
            return false;
        }
        hashOps.delete(KEY, labelid);
        return true;
    }

    //查询所有的标签
    @Override
    public Object findAllLabels() {
        Collection values = hashOps.entries(KEY).values();
        if(values==null||values.size()<=0) {
            return null;
        }
        return values;
    }

    //根据标签id查询单个标签
    @Override
    public PoolLabel findOne(Integer labelid) {

        return (PoolLabel)hashOps.get(KEY, labelid);
    }


    //批量保存
    @Override
    public boolean saveAll(List<PoolLabel> labels) {
        if(labels==null||labels.size()==0){
            return false;
        }
        for(PoolLabel temp:labels){
            saveLabel(temp);
        }
        return true;
    }

    //批量保存 重载
    @Override
    public boolean saveAll(Iterator<PoolLabel> labels) {
        if(labels==null){
            return false;
        }
        while (labels.hasNext()) {
            saveLabel(labels.next());
        }
        return true;
    }
}
